package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.*;
import com.sky.result.Result;
import com.sky.service.OrdersService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;



    @Override
    public Result addorders(OrdersSubmitDTO ordersSubmitDTO) {
        if (ordersSubmitDTO ==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        Long userId = BaseContext.getCurrnetId();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getByUserId(userId);
        //  判断数据库 是否有数据
        if (shoppingCartList.size() ==0){
            return Result.success();
        }

        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        String orderId= userId + "" + System.currentTimeMillis();
        LocalDateTime now = LocalDateTime.now();
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders = orders.toBuilder().number(orderId)
                .status(1)
                .userId(userId)
                .orderTime(now)
                .phone(addressBook.getPhone())
                .address(addressBook.getDetail())
                .userName(userMapper.getById(userId).getName())
                .cancelReason(addressBook.getConsignee())
                .build();
        ordersMapper.addorders(orders);

        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderAmount(ordersSubmitDTO.getAmount());
        orderSubmitVO.setOrderNumber(orderId);
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(now);



        return Result.success(orderSubmitVO);

    }
}
